package com.blackbox.price.util;

import com.blackbox.price.configuration.VisionException;
import org.apache.commons.io.filefilter.SuffixFileFilter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @Author: ganlinxin
 * @Description:
 * @Date: Created in 13:40 2018/11/15
 * @Modidied By:
 */
@Component
public class FileUploadUtil {

    private static FileUploadUtil util;

    @Value("${fileUpload.root:D:}")
    private String path;
    @Value("${fileUpload.fileOrmPath:D}")
    private String ormPath;

    private FileUploadUtil() {

    }

    public static FileUploadUtil getUtil() {
        return util;
    }

    //@PostConstruct
    public void init() {
        util = this;
    }

    public String fileUpload(MultipartFile file, String type, SuffixFileFilter filter) throws Exception {
        if (!new File(path + type).exists()) {
            new File(path + type).mkdirs();
        }
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.')).toLowerCase();
        String newName = UUID.randomUUID().toString().replaceAll("-", "") + suffix;
        File fj = new File(path + type + "/" + newName);
        if (filter != null && !filter.accept(fj)) {
            throw new VisionException("不允许该格式");
        }
        file.transferTo(fj);
        return ormPath + type + "/" + newName;
    }

    public String imgUpload(MultipartFile file) throws Exception {
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.')).toLowerCase();
        String newName = UUID.randomUUID().toString().replaceAll("-", "") + suffix;
        File fj = new File( "D://Upload/" + newName);
        file.transferTo(fj);
        return newName;
    }

    /**
     * @param request
     * @param fileIndetity
     * @param path
     * @return
     * @throws IOException
     */
    public String uploadFile(HttpServletRequest request, String fileIndetity, String path, String[] limit) throws Exception {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultiValueMap<String, MultipartFile> multiFileMap = multipartRequest.getMultiFileMap();
        List<MultipartFile> fileList = multiFileMap.get(fileIndetity);
        StringBuilder stringBuilder = new StringBuilder();
        SuffixFileFilter filter = null;
        if (limit.length > 0) {
            filter = new SuffixFileFilter(limit);
        }
        if (fileList != null && !fileList.isEmpty()) {
            for (MultipartFile file : fileList) {
                // 文件保存路径
                String uploadPath = util.fileUpload(file, path, filter);
                stringBuilder.append(uploadPath).append("&");
            }
            return stringBuilder.toString().substring(0, stringBuilder.length() - 1);
        } else {
            return "";
        }

    }

    //返回文件名原名和现有路径

    /**文件上传
     * @param request
     * @param fileIndetity
     * @param path
     * @return
     * @throws IOException
     */
    public Map<String,String> uploadFile(HttpServletRequest request, String fileIndetity, String path, String[] limit,
                                         boolean oldName) throws Exception {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultiValueMap<String, MultipartFile> multiFileMap = multipartRequest.getMultiFileMap();
        List<MultipartFile> fileList = multiFileMap.get(fileIndetity);
        SuffixFileFilter filter = null;
        Map<String,String> fileMap = new HashMap<>();
        if (limit.length > 0) {
            filter = new SuffixFileFilter(limit);
        }
        if (fileList != null && !fileList.isEmpty()) {
            for (MultipartFile file : fileList) {
                // 文件保存路径
                Map<String, String> stringStringMap = util.fileUpload(file, path, filter, oldName);
                fileMap.put(stringStringMap.get("newName"),stringStringMap.get("oldName"));
            }
        }
        return fileMap ;
    }


    public Map<String,String> fileUpload(MultipartFile file, String type, SuffixFileFilter filter, boolean oldName) throws Exception {
        if (!new File(path + type).exists()) {
            new File(path + type).mkdirs();
        }
        String originalFilename = file.getOriginalFilename();
        Assert.notNull(originalFilename,"file.getOriginalFilename() return null");
        String suffix = originalFilename.substring(originalFilename.lastIndexOf('.')).toLowerCase();
        String newName = originalFilename + "_" + System.currentTimeMillis() + suffix;
        File fj = new File(path + type + "/" + newName);
        if (filter != null && !filter.accept(fj)) {
            throw new VisionException("不允许该格式");
        }
        file.transferTo(fj);
        Map<String,String> result = new HashMap<>();
        result.put("newName",ormPath + type + "/" + newName);
        result.put("oldName",originalFilename);
        return result;
    }


    public static List<String> getFileName(String path) {
        File file = new File(path);
        return Arrays.asList(Objects.requireNonNull(file.list()));
    }
}
